package at.fhj.itm10.ticketmaster.beans;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;


import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


import at.fhj.itm10.ticketmaster.dao.CustomerDAO;
import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.dao.DAOFactory;
import at.fhj.itm10.ticketmaster.dao.impl.DAOFactoryImpl;
import at.fhj.itm10.ticketmaster.helper.MD5Hashmaker;
import at.fhj.itm10.ticketmaster.models.Customer;

/**
 * @author Martin Gritsch
 * @since November 2012
 */
@ManagedBean
@SessionScoped

public class LoginBean {
	
	private CustomerDAO dao;
	private Customer customer;
	
	private String email;
	private String password;
	private String username;
	private boolean isLoggedIn;
	private List<Customer> customers = new ArrayList<Customer>();
	
	public LoginBean() {
		this.init();
	}

	@PostConstruct
	public void init() {
    	try {
			DAOFactory daoFactoryImpl;
			daoFactoryImpl = new DAOFactoryImpl();
			setDao(daoFactoryImpl.getCustomerDAO());
		}
    	catch (DAOException e) {
			e.printStackTrace();
		}
	}

	public String login() {
		try {
			this.customers = this.dao.findByEMail(this.email);
			if (this.customers.size() == 0) {
				this.setLoggedIn(false);
				return "NotLoggedIn";
			}
			else if ((this.customers.get(0).getPassword().equals(MD5Hashmaker.generateMD5Code(this.password))) && (this.customers.get(0).isActivated())) {
					this.setLoggedIn(true);
					this.setCustomer(this.customers.get(0));
					return "LoggedIn";
			}
			else {
				this.setLoggedIn(false);
				return "NotLoggedIn";
			}
		}
		catch (DAOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "NotLoggedIn";
    }
	
    public String getEmail() {
    	return this.email;
    }
    public void setEmail(String username) {
    	this.email = username;
    }

    public String getPassword() {
    	return this.password;
    }
    public void setPassword(String password) {
    	this.password = password;
    }
    
    public Customer getCustomer() {
		return this.customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
    
    public CustomerDAO getDao() {
		return this.dao;
	}
	public void setDao(CustomerDAO dao) {
		this.dao = dao;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
	}
}
